package cn.netjava.softkid.chapter11;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
public class PortScanner{
	
	public void scanPort()
	{
		JFrame jf = new JFrame();
		jf.setSize(400, 300);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		//a button  press it and start scan
		button = new JButton("start");
		
		labelOne = new JLabel("please enter an ip address");
		labelTwo = new JLabel("opened port:");
		field1 = new JTextField("127.0.0.1",10);
		field2 = new JTextField("From",5);
		field3 = new JTextField("To",5);
		field4 = new JTextField("Thread Number",10);
		bar = new JProgressBar();
		bar.setMaximum(100);
		bar.setMinimum(0);
		int a =0;
		
		area = new JTextArea(5,20);
		
		jf.setLayout(new FlowLayout());
		jf.add(labelOne);
		jf.add(field1);
		jf.add(field2);
		jf.add(field3);
		jf.add(field4);
		jf.add(button);
		jf.add(labelTwo);
		jf.add(area);
		jf.add(bar);
		
		button.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					processEvent();
				}
			}
		);
		
		jf.setVisible(true);
		for(int i=0;i<100;i++)
		{
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			bar.setValue(a);
			bar.setStringPainted(true);
			a+=1;
		}
		
	}
	
	public void processEvent()
	{
		String ip = field1.getText();
		System.out.println(ip);
		int from = Integer.parseInt(field2.getText());
		int to = Integer.parseInt(field3.getText());
		int num = Integer.parseInt(field4.getText());
		int temp = (to-from)/num;
		for(int i=1;i<=num;i++)
		{
			ScannerThread st = new ScannerThread(from,from+temp,ip);
			from+=temp;
			st.start();
			
		}
	}
	public static void main(String[] args)
	{
		PortScanner ps = new PortScanner();
		ps.scanPort();

	}
	private JButton button;
	private JLabel labelOne;
	private JLabel labelTwo;
	private JTextField field1;
	private JTextField field2;
	private JTextField field3;
	private JTextField field4;
	static JTextArea area;
	private JProgressBar bar;

}
